//
//  XXMathFuntion.swift
//  MOMAEducation
//
//  Created by Rdxer on 2017/11/27.
//  Copyright © 2017年 Rdxer. All rights reserved.
//

import UIKit

public struct XXMathLibrary {
    
    /// 限制只能在此区间
    public static func absLimit(_ value:CGFloat,min:CGFloat,max:CGFloat) -> CGFloat{
        
        if value < min{
            return min
        }
        
        if value > max{
            return max
        }
        
        return value
    }
    
    /// 通道转换
    public static func channelConversion(_ value:CGFloat,inputMin:CGFloat,inputMax:CGFloat,outputMin:CGFloat,outputMax:CGFloat,isStrictMode:Bool = false) -> CGFloat{
        // 归零
        let absValue = value - inputMin
        
        if isStrictMode && absValue < 0.000001{
            return outputMin
        }
        
        // 输入区间
        let inputRange = inputMax - inputMin
        // 输入区间的游标比例
        let positionScale = absValue / inputRange
        
        // 输出区间
        let outputRange = outputMax - outputMin
        // 输出区间的游标值
        let outAbsValue = outputRange * positionScale
        
        
        let returnValue = outAbsValue + outputMin
        
        if isStrictMode && outAbsValue < 0.000001{
            return outputMin
        }
        
        return returnValue
    }
}

public extension XXMathLibrary {
    public   struct Random {
        
        /// 生成随机数 [min,max)
        ///
        /// - Parameters:
        ///   - min: 最小 (default value: 0)
        ///   - max: 最大
        public static func random(min:Int = 0,max:Int)->Int{
            let difference = max - min
            let rv = Int(arc4random_uniform(UInt32(difference)))
            return rv + min
        }
        
        /// 生成随机数 [0,1]
        ///
        /// - Parameters:
        ///   - significantFigures: 有效数字 (default value: 3)
        public static func randomDouble(significantFigures:Int = 3)->Double{
            
            let intMax = Int(pow(10, Double(significantFigures)))
            
            let rv = random(max: intMax)
            
            let rv_double = Double(rv)/Double(intMax)
            
            return rv_double
        }
        
        
        /// 生成随机数 [0,1]
        ///
        /// - Parameters:
        ///   - significantFigures: 有效数字 (default value: 3)
        public static func randomUnitValue<T:XXFloat>(significantFigures:Int = 3)->T{
            return T.from(randomDouble(significantFigures:significantFigures)) as! T
        }
        
    }
    
    
    
}


public protocol XXFloat {
    associatedtype CompatibleXXFloatType
    static func from(_ v:Double)->CompatibleXXFloatType
}
extension CGFloat:XXFloat{
    public   static func from(_ v: Double) -> CGFloat {
        return CGFloat.init(v)
    }
}

extension Double:XXFloat{
    public  static func from(_ v: Double) -> Double {
        return Double.init(v)
    }
}

extension Float:XXFloat{
    public static func from(_ v: Double) -> Float {
        return Float.init(v)
    }
}
